package com.ysd.lis.service.inti.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.entity.bac.*;
import com.ysd.lis.entity.inti.IntInstrGermResult;
import com.ysd.lis.entity.inti.IntInstrGermResultLog;
import com.ysd.lis.entity.lab.LabMaininfo;
import com.ysd.lis.mapper.bac.*;
import com.ysd.lis.mapper.inti.IntInstrGermResultMapper;
import com.ysd.lis.mapper.lab.LabMaininfoMapper;
import com.ysd.lis.request.SysParamFieldValueDto;
import com.ysd.lis.request.SysParamParam;
import com.ysd.lis.request.inti.IntinstrGermReusltDto;
import com.ysd.lis.request.lab.IntInstrResultParam;
import com.ysd.lis.service.SysParamValueService;
import com.ysd.lis.service.bac.BacDrugTestResultService;
import com.ysd.lis.service.bac.BacInstrAntibDictService;
import com.ysd.lis.service.bac.BacInstrGermDictService;
import com.ysd.lis.service.bac.BacTestResultService;
import com.ysd.lis.service.bac.impl.BacBreakPointCalcServiceImpl;
import com.ysd.lis.service.inti.IntInstrGermResultLogService;
import com.ysd.lis.service.inti.IntInstrGermResultService;
import com.ysd.lis.service.lab.LabMaininfoService;
import com.ysd.util.ToolsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Bai
 * @since 2024-11-25
 */
@Service
public class IntInstrGermResultServiceImpl extends ServiceImpl<IntInstrGermResultMapper, IntInstrGermResult> implements IntInstrGermResultService {
    @Autowired
    IntInstrGermResultMapper intInstrGermResultMapper;
    @Autowired
    LabMaininfoMapper labMaininfoMapper;
    @Autowired
    LabMaininfoService labMaininfoService;
    @Autowired
    BacTestResultService bacTestResultService;
    @Autowired
    BacGermDictMapper bacGermDictMapper;
    @Autowired
    IntInstrGermResultLogService intInstrGermResultLogService;
    @Autowired
    BacDrugTestResultService bacDrugTestResultService;
    @Autowired
    BacAntibioticsDictMapper bacAntibioticsDictMapper;
    @Autowired
    BacTestWorkFlowNodeMapper bacTestWorkFlowNodeMapper;
    @Autowired
    BacWorkFlowNodeMapper bacWorkFlowNodeMapper;
    @Autowired
    BacTestWorkFlowMapper bacTestWorkFlowMapper;
    @Autowired
    BacBreakPointCalcServiceImpl bacBreakPointCalcService;
    @Autowired
    BacSiteOfInfectionDictMapper bacSiteOfInfectionDictMapper;
    @Override
    public Result transIntInstrGermResult() {
        //从结果表中按照最新的时间查出500条数据
        Page<IntInstrGermResult> page = new Page<>();
        page.setCurrent(1);
        page.setSize(500);
        Calendar calendar = Calendar.getInstance(); // 获取当前日期的Calendar实例
        Date today = calendar.getTime();
        //取500条数据
        LambdaQueryWrapper<IntInstrGermResult> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .and(p -> p.eq(IntInstrGermResult::getDataType, "W").or().eq(IntInstrGermResult::getDataType, "Q"))
                .and(p -> p.eq(IntInstrGermResult::getIsNoChannel, "N").or().isNull(IntInstrGermResult::getIsNoChannel))
                .isNotNull(IntInstrGermResult::getInstrCode)
                .ge(IntInstrGermResult::getCreateTime, DateUtil.beginOfDay(today).toTimestamp())
                .le(IntInstrGermResult::getCreateTime, DateUtil.endOfDay(today).toTimestamp())
                .orderByAsc(IntInstrGermResult::getCreateTime);
        Page<IntInstrGermResult> intInstrGermResultPage = intInstrGermResultMapper.selectPage(page, queryWrapper);
        List<IntInstrGermResult> intInstrGermResults = intInstrGermResultPage.getRecords();
        if (ToolsUtils.isNotEmpty(intInstrGermResults)) {
            //数据类型：W、微生物检验结果数据；Q、抗生素结果数据
            //先查出 W、微生物检验结果数据；
            List<IntInstrGermResult> wInstrGermResultList = intInstrGermResults.stream().filter(s -> "W".equals(s.getDataType())).collect(Collectors.toList());
            if (ToolsUtils.isNotEmpty(wInstrGermResultList)) {
                transBacRptresult(wInstrGermResultList);
            }

            //查出Q、抗生素结果数据
            List<IntInstrGermResult> qInstrGermResultList = intInstrGermResults.stream().filter(s -> "Q".equals(s.getDataType())).collect(Collectors.toList());
            if (ToolsUtils.isNotEmpty(qInstrGermResultList)) {
                transBacDrugTestResult(qInstrGermResultList);
            }

        }

        new Thread(() -> {
            this.removeIntInstrGermResult();
        }).start();

        return Result.succ(1, "同步结果成功", null);

    }

    private void removeIntInstrGermResult() {
        //删除创建时间30天之前的数据
        LambdaQueryWrapper<IntInstrGermResult> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.le(IntInstrGermResult::getCreateTime, DateUtil.offsetDay(new Date(), -30));
        this.remove(queryWrapper);
        //删除INT_INSTR_GERM_RESULT_LOG表中30天之前的数据
        LambdaQueryWrapper<IntInstrGermResultLog> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.le(IntInstrGermResultLog::getCreateTime, DateUtil.offsetDay(new Date(), -30));
        intInstrGermResultLogService.remove(queryWrapper1);
    }

    private void transBacRptresult(List<IntInstrGermResult> wInstrGermResultList) {
        //未维护通道号的数据
        List<IntInstrGermResult> noChannelResultList = new ArrayList<>();
        //需要删除且转移到log表中的数据
        List<IntInstrGermResult> delInstrGermResultList = new ArrayList<>();

        //按照sampleDa,prtGroup,sampleNo orgId分组
        Map<List<Object>, List<IntInstrGermResult>> instrGermResultMap
                = wInstrGermResultList.stream().collect(Collectors.groupingBy(s -> Arrays.asList(s.getSampleda(), s.getRptGroup(), s.getSampleNo(), s.getOrgId())));
        //按照一个上级记录分组，查询出对应的所有子记录
        for (List<Object> mainInfolist : instrGermResultMap.keySet()) {
            Timestamp sampleda = null;
            String rptGroup = "";
            String sampleNo = "";
            String orgId = "";
            if (ToolsUtils.isNotEmpty(mainInfolist.get(0))) {
                sampleda = (Timestamp) mainInfolist.get(0);
            }
            if (ToolsUtils.isNotEmpty(mainInfolist.get(1))) {
                rptGroup = String.valueOf(mainInfolist.get(1));
            }
            if (ToolsUtils.isNotEmpty(mainInfolist.get(2))) {
                sampleNo = String.valueOf(mainInfolist.get(2));
            }
            if (ToolsUtils.isNotEmpty(mainInfolist.get(3))) {
                orgId = String.valueOf(mainInfolist.get(3));
            }
            if (ToolsUtils.isNotEmpty(sampleda) && ToolsUtils.isNotEmpty(rptGroup) && ToolsUtils.isNotEmpty(sampleNo) && ToolsUtils.isNotEmpty(orgId)) {
                //找到对应得报告单元

                //按照分组后的数据生成labMaininfo数据
                LabMaininfo labMaininfo = null;

                String format = DateUtil.format(sampleda, "yyyy-MM-dd");
                Timestamp startTime = Timestamp.valueOf(format + " 00:00:00");
                Timestamp endTime = Timestamp.valueOf(format + " 23:59:59");

                //优先按条码号查询
                LambdaQueryWrapper<LabMaininfo> queryWrapper2 = new LambdaQueryWrapper<>();
                queryWrapper2.eq(LabMaininfo::getDelFlag, 0)
                        .eq(LabMaininfo::getRptGroup, rptGroup)
//                        .ge(LabMaininfo::getSampleda, startTime)
//                        .le(LabMaininfo::getSampleda, endTime)
                        .eq(LabMaininfo::getReqNo, sampleNo)
                        .eq(LabMaininfo::getOrgId, orgId);
                List<LabMaininfo> maininfoList = labMaininfoMapper.selectList(queryWrapper2);
                if (ToolsUtils.isNotEmpty(maininfoList)) {
                    labMaininfo = maininfoList.get(0);
                } else {
                    //标本号查询
                    LambdaQueryWrapper<LabMaininfo> queryWrapper3 = new LambdaQueryWrapper<>();
                    queryWrapper3.eq(LabMaininfo::getDelFlag, 0)
                            .eq(LabMaininfo::getRptGroup, rptGroup)
//                            .ge(LabMaininfo::getSampleda, startTime)
//                            .le(LabMaininfo::getSampleda, endTime)
                            .eq(LabMaininfo::getSampleNo, sampleNo)
                            .eq(LabMaininfo::getOrgId, orgId);
                    List<LabMaininfo> maininfoList1 = labMaininfoMapper.selectList(queryWrapper3);
                    if (ToolsUtils.isNotEmpty(maininfoList1)) {
                        labMaininfo = maininfoList1.get(0);
                    }
                }
                //无工作列表新建工作列表
                if (null == labMaininfo) {
                    labMaininfo = new LabMaininfo();
                    labMaininfo.setRptGroup(rptGroup);
                    labMaininfo.setSampleda(startTime);
                    labMaininfo.setSampleNo(sampleNo);
                    labMaininfo.setTestTime(new Timestamp(System.currentTimeMillis()));
                    labMaininfo.setIsChk(new BigDecimal(0));
                    labMaininfo.setOrgId(orgId);
                    LambdaQueryWrapper<LabMaininfo> lambdaQueryWrappers = new LambdaQueryWrapper<>();
                    lambdaQueryWrappers
                            .eq(LabMaininfo::getSampleNo, sampleNo)
                            .eq(LabMaininfo::getRptGroup, rptGroup)
                            .ge(LabMaininfo::getSampleda, startTime)
                            .le(LabMaininfo::getSampleda, endTime)
                            .eq(LabMaininfo::getOrgId, orgId)
                            .eq(LabMaininfo::getDelFlag, 0);
                    boolean b = labMaininfoService.saveOrUpdate(labMaininfo, lambdaQueryWrappers);
                }

                BigDecimal isChk = labMaininfo.getIsChk();
                if (ToolsUtils.isNotEmpty(isChk) && isChk.intValue() > 0) {
                    delInstrGermResultList.addAll(instrGermResultMap.get(mainInfolist));
                    continue;
                }

                //处理结果列表=======
                //接口结果列表 //逆序
                List<IntInstrGermResult> intGermResultList = instrGermResultMap.get(mainInfolist)
                        .stream().sorted(Comparator.comparing(IntInstrGermResult::getCreateTime).reversed()).collect(Collectors.toList());
                //根据germNo、isolateNum，germMachineNo去重
                List<IntInstrGermResult> intInstrGermResultList = intGermResultList
                        .stream().collect(Collectors.collectingAndThen(Collectors
                                .toCollection(() -> new TreeSet<>(Comparator.comparing(IntInstrGermResult::getGermNo).thenComparing(IntInstrGermResult::getIsolateNum).thenComparing(IntInstrGermResult::getGermMachineNo))), ArrayList::new));

                //去重之后需要把去重得数据找出来 放到删除并转移到log表中的集合中
                List<IntInstrGermResult> quchongList = intGermResultList.stream().filter(item -> !intInstrGermResultList.contains(item)).collect(Collectors.toList());
                if (ToolsUtils.isNotEmpty(quchongList)) {
                    delInstrGermResultList.addAll(quchongList);
                }
                //查询工作列表结果
                LambdaQueryWrapper<BacTestResult> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(BacTestResult::getDelFlag, 0)
                        .eq(BacTestResult::getRptGroup, rptGroup)
//                        .ge(BacTestResult::getSampleda, startTime)
//                        .le(BacTestResult::getSampleda, endTime)
                        .eq(BacTestResult::getSampleNo, labMaininfo.getSampleNo())
                        .eq(BacTestResult::getOrgId, orgId);
                List<BacTestResult> testResultList = bacTestResultService.list(queryWrapper);

                //查询微生物检验应用流程方案节点
                MPJLambdaWrapper<BacTestWorkFlowNode> queryWorkFlowNodeWrapper = new MPJLambdaWrapper<>();
                String finalRptGroup = rptGroup;
                String finalSampleNo = labMaininfo.getSampleNo();
                LabMaininfo finalLabMaininfo = labMaininfo;
                queryWorkFlowNodeWrapper.selectAll(BacTestWorkFlowNode.class)
                        .innerJoin(BacTestWorkFlow.class, "TF", p -> p.eq(BacTestWorkFlow::getDelFlag, 0)
                                .eq(BacTestWorkFlow::getRptGroup, finalRptGroup)
                                .eq(BacTestWorkFlow::getSampleNo, finalSampleNo)
//                                .ge(BacTestWorkFlow::getSampleda, startTime)
//                                .le(BacTestWorkFlow::getSampleda, endTime)
                                //.eq(BacTestWorkFlow::getReqNo, finalLabMaininfo.getReqNo())
                                .eq(BacTestWorkFlow::getWorkFlowNo, BacTestWorkFlowNode::getTestFlowNo)
                                .eq(BacTestWorkFlow::getOrgId, BacTestWorkFlowNode::getOrgId))
                        .innerJoin(BacWorkFlowNode.class, "FN", p -> p.eq(BacWorkFlowNode::getDelFlag, 0)
                                .eq(BacWorkFlowNode::getFlowNo, BacTestWorkFlowNode::getTestFlowNo)
                                .eq(BacWorkFlowNode::getNodeCode, BacTestWorkFlowNode::getNodeNo)
                                .eq(BacWorkFlowNode::getOrgId, BacTestWorkFlowNode::getOrgId))
                        .innerJoin(BacWorkFlowNodeDict.class, "ND", p -> p.eq(BacWorkFlowNodeDict::getDelFlag, 0)
                                .eq(BacWorkFlowNodeDict::getCode, BacTestWorkFlowNode::getNodeNo)
                                .eq(BacWorkFlowNodeDict::getOrgId, BacTestWorkFlowNode::getOrgId)
                                .eq(BacWorkFlowNodeDict::getPageCode, "RptResultBac"))
                        .eq(BacTestWorkFlowNode::getDelFlag, 0)
                        .eq(BacTestWorkFlowNode::getRptGroup, finalRptGroup)
                        .eq(BacTestWorkFlowNode::getSampleNo, finalSampleNo)
                        .eq(BacTestWorkFlowNode::getOrgId, orgId);
                List<BacTestWorkFlowNode> bacTestWorkFlowNodeList = bacTestWorkFlowNodeMapper.selectList(queryWorkFlowNodeWrapper);
                BacTestWorkFlowNode bacTestWorkFlowNode = null;
                if (ToolsUtils.isNotEmpty(bacTestWorkFlowNodeList)) {
                    bacTestWorkFlowNode = bacTestWorkFlowNodeList.get(0);
                } else {
                    //查找默认方案 插入数据 BacTestWorkFlow BacTestWorkFlowNo
                    MPJLambdaWrapper<BacWorkFlowNode> queryFlowNodeWrapper = new MPJLambdaWrapper<>();
                    queryFlowNodeWrapper.selectAll(BacWorkFlowNode.class)
                            .selectAs("bf", BacWorkFlow::getWorkFlowName, BacWorkFlowNode::getFlowNa)
                            .innerJoin(BacWorkFlow.class, "bf", p -> p.eq(BacWorkFlow::getDelFlag, 0)
                                    .eq(BacWorkFlow::getWorkFlowCode, BacWorkFlowNode::getFlowNo).eq(BacWorkFlow::getWorkFlowCode, "mrfa"))
                            .innerJoin(BacWorkFlowNodeDict.class, "nd", p -> p.eq(BacWorkFlowNodeDict::getDelFlag, 0)
                                    .eq(BacWorkFlowNodeDict::getCode, BacWorkFlowNode::getNodeDictNo).eq(BacWorkFlowNodeDict::getPageCode, "RptResultBac"))
                            .eq(BacWorkFlowNode::getDelFlag, 0)
                            .eq(BacWorkFlowNode::getOrgId, orgId);
                    List<BacWorkFlowNode> bacWorkFlowNodeList = bacWorkFlowNodeMapper.selectList(queryFlowNodeWrapper);
                    if (ToolsUtils.isNotEmpty(bacWorkFlowNodeList)) {
                        BacWorkFlowNode bacWorkFlowNode = bacWorkFlowNodeList.get(0);
                        BacTestWorkFlow bacTestWorkFlow = new BacTestWorkFlow();
                        bacTestWorkFlow.setReqNo(labMaininfo.getReqNo());
                        bacTestWorkFlow.setWorkFlowNo(bacWorkFlowNode.getFlowNo());
                        bacTestWorkFlow.setWorkFlowNa(bacWorkFlowNode.getFlowNa());
                        bacTestWorkFlow.setSeq(1);
                        bacTestWorkFlow.setOrgId(labMaininfo.getOrgId());
                        bacTestWorkFlow.setSampleNo(labMaininfo.getSampleNo());
                        bacTestWorkFlow.setSampleda(labMaininfo.getSampleda());
                        bacTestWorkFlow.setRptGroup(rptGroup);
                        bacTestWorkFlowMapper.insert(bacTestWorkFlow);

                        bacTestWorkFlowNode = new BacTestWorkFlowNode();
                        bacTestWorkFlowNode.setOrgId(labMaininfo.getOrgId());
                        bacTestWorkFlowNode.setTestFlowNo(bacWorkFlowNode.getFlowNo());
                        bacTestWorkFlowNode.setNodeNo(bacWorkFlowNode.getNodeCode());
                        bacTestWorkFlowNode.setReqNo(labMaininfo.getReqNo());
                        bacTestWorkFlowNode.setSampleNo(labMaininfo.getSampleNo());
                        bacTestWorkFlowNode.setSampleda(labMaininfo.getSampleda());
                        bacTestWorkFlowNode.setRptGroup(rptGroup);
                        bacTestWorkFlowNodeMapper.insert(bacTestWorkFlowNode);
                    }

                }

                List<BacTestResult> saveOrUpdateResultList = new ArrayList<>();

                //查看上机记录上有没有感染部位信息 如果有 查询感染部位表查出对应的感染部位对象
                BacSiteOfInfectionDict siteOfInfectionDict = null;
                if(ToolsUtils.isNotEmpty(labMaininfo.getInfectSiteNo())){
                    LambdaQueryWrapper<BacSiteOfInfectionDict> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(BacSiteOfInfectionDict::getDelFlag, 0)
                            .eq(BacSiteOfInfectionDict::getCode, labMaininfo.getInfectSiteNo())
                            .eq(BacSiteOfInfectionDict::getOrgId, orgId);
                    List<BacSiteOfInfectionDict> siteOfInfectionDictList = bacSiteOfInfectionDictMapper.selectList(wrapper);
                    if(ToolsUtils.isNotEmpty(siteOfInfectionDictList)){
                        siteOfInfectionDict = siteOfInfectionDictList.get(0);
                    }
                }
                for (IntInstrGermResult intInstrGermResult : intInstrGermResultList) {
                    //根据 germMachineNo与germNo查找对照表
                    String germMachineNo = intInstrGermResult.getGermMachineNo();
                    String germNo = intInstrGermResult.getGermNo();
                    String resultOrgId = intInstrGermResult.getOrgId();
                    MPJLambdaWrapper<BacGermDict> queryGermDictWrapper = new MPJLambdaWrapper<>();
                    queryGermDictWrapper.selectAll(BacGermDict.class)
                            .innerJoin(BacInstrGermDict.class, p -> p.eq(BacInstrGermDict::getInstrCode, germMachineNo)
                                    .eq(BacInstrGermDict::getInputGermNo, germNo)
                                    .eq(BacInstrGermDict::getOrgId, resultOrgId)
                                    .eq(BacInstrGermDict::getDelFlag, 0)
                                    .eq(BacInstrGermDict::getGermNo, BacGermDict::getGermNo))
                            .eq(BacGermDict::getDelFlag, 0);
                    List<BacGermDict> germDictList = bacGermDictMapper.selectJoinList(BacGermDict.class, queryGermDictWrapper);
                    if (ToolsUtils.isNotEmpty(germDictList)) {
                        BacTestResult bacTestResult;
                        //查看结果表中是否有结果
                        String isolateNum = intInstrGermResult.getIsolateNum();
                        BacGermDict bacGermDict = germDictList.get(0);
                        Optional<BacTestResult> testResultOptional = testResultList.stream().filter(item -> ToolsUtils.isNotEmpty(item.getIsolateNum()) && item.getIsolateNum().equals(isolateNum) && item.getGermNo().equals(bacGermDict.getGermNo())).findFirst();
                        if (testResultOptional.isPresent()) {
                            bacTestResult = testResultOptional.get();
                        } else {
                            bacTestResult = new BacTestResult();
                            bacTestResult.setSampleda(labMaininfo.getSampleda());
                            bacTestResult.setSampleNo(labMaininfo.getSampleNo());
                            bacTestResult.setRptGroup(rptGroup);
                            bacTestResult.setOrgId(resultOrgId);
                            bacTestResult.setIsolateNum(isolateNum);
                            bacTestResult.setGermNo(bacGermDict.getGermNo());
                            bacTestResult.setGermNa(bacGermDict.getGermNa());
                            if (ToolsUtils.isNotEmpty(bacTestWorkFlowNode)) {
                                bacTestResult.setTestFlowNo(bacTestWorkFlowNode.getTestFlowNo());
                                bacTestResult.setTestNodeNo(bacTestWorkFlowNode.getNodeNo());
                            }
                            Timestamp operatedate = intInstrGermResult.getOperatedate();
                            if (ToolsUtils.isNotEmpty(operatedate)) {
                                bacTestResult.setOperateDate(operatedate);
                            } else {
                                bacTestResult.setOperateDate(new Timestamp(new Date().getTime()));//
                            }
                            bacTestResult.setInfeSiteNo(labMaininfo.getInfectSiteNo());
                            if(ToolsUtils.isNotEmpty(siteOfInfectionDict)){
                                bacTestResult.setInfeSiteNa(siteOfInfectionDict.getName());
                            }
                        }
                        bacTestResult.setTestResult(intInstrGermResult.getResult());
                        if(ToolsUtils.isNotEmpty(intInstrGermResult.getBz())){
                            bacTestResult.setTestResult(intInstrGermResult.getBz());
                        }
                        bacTestResult.setIntResultId(intInstrGermResult.getId());
                        bacTestResult.setInstrCode(intInstrGermResult.getInstrCode());
                        bacTestResult.setGermMachineNo(intInstrGermResult.getGermMachineNo());
                        saveOrUpdateResultList.add(bacTestResult);
                        //将成功插入结果表中得数据转移到log表中
                        delInstrGermResultList.add(intInstrGermResult);

                    } else {
                        //无通道号
                        intInstrGermResult.setIsNoChannel("G");
                        noChannelResultList.add(intInstrGermResult);
                    }

                }//接口结果循环完毕

                if (ToolsUtils.isNotEmpty(saveOrUpdateResultList)) {
                    boolean isSaveOrupdate = bacTestResultService.saveOrUpdateBatch(saveOrUpdateResultList);
                }


            }//sampleDa,prtGroup,sampleNo都不为空
        }//循环结束
        if (ToolsUtils.isNotEmpty(delInstrGermResultList)) {
            //删除
            List<String> ids = delInstrGermResultList.stream().map(IntInstrGermResult::getId).collect(Collectors.toList());
            this.removeByIds(ids);
            //插入log
            List<IntInstrGermResultLog> addLogList = new ArrayList<>();
            for (IntInstrGermResult iResult : delInstrGermResultList) {
                IntInstrGermResultLog resultLog = new IntInstrGermResultLog();
                BeanUtil.copyProperties(iResult, resultLog, "id");
                resultLog.setInstrGermResultId(iResult.getId());
                addLogList.add(resultLog);
            }
            intInstrGermResultLogService.saveBatch(addLogList);
        }
        if (ToolsUtils.isNotEmpty(noChannelResultList)) {
            this.updateBatchById(noChannelResultList);
        }
    }

    private void transBacDrugTestResult(List<IntInstrGermResult> qInstrGermResultList) {

        //未维护通道号的数据
        List<IntInstrGermResult> noChannelResultList = new ArrayList<>();
        //需要删除且转移到log表中的数据
        List<IntInstrGermResult> delInstrGermResultList = new ArrayList<>();

        //按照sampleDa,prtGroup,sampleNo orgId分组
        Map<List<Object>, List<IntInstrGermResult>> instrGermResultMap
                = qInstrGermResultList.stream().collect(Collectors.groupingBy(s -> Arrays.asList(s.getSampleda(), s.getRptGroup(), s.getSampleNo(), s.getOrgId())));
        //按照一个上级记录分组，查询出对应的所有子记录
        for (List<Object> mainInfolist : instrGermResultMap.keySet()) {
            Timestamp sampleda = null;
            String rptGroup = "";
            String sampleNo = "";
            String orgId = "";
            if (ToolsUtils.isNotEmpty(mainInfolist.get(0))) {
                sampleda = (Timestamp) mainInfolist.get(0);
            }
            if (ToolsUtils.isNotEmpty(mainInfolist.get(1))) {
                rptGroup = String.valueOf(mainInfolist.get(1));
            }
            if (ToolsUtils.isNotEmpty(mainInfolist.get(2))) {
                sampleNo = String.valueOf(mainInfolist.get(2));
            }
            if (ToolsUtils.isNotEmpty(mainInfolist.get(3))) {
                orgId = String.valueOf(mainInfolist.get(3));
            }
            if (ToolsUtils.isNotEmpty(sampleda) && ToolsUtils.isNotEmpty(rptGroup) && ToolsUtils.isNotEmpty(sampleNo) && ToolsUtils.isNotEmpty(orgId)) {
                //按照分组后的数据生成labMaininfo数据
                LabMaininfo labMaininfo = null;
                String format = DateUtil.format(sampleda, "yyyy-MM-dd");
                Timestamp startTime = Timestamp.valueOf(format + " 00:00:00");
                Timestamp endTime = Timestamp.valueOf(format + " 23:59:59");

                //优先按条码号查询
                LambdaQueryWrapper<LabMaininfo> queryWrapper2 = new LambdaQueryWrapper<>();
                queryWrapper2.eq(LabMaininfo::getDelFlag, 0)
                        .eq(LabMaininfo::getRptGroup, rptGroup)
//                        .ge(LabMaininfo::getSampleda, startTime)
//                        .le(LabMaininfo::getSampleda, endTime)
                        .eq(LabMaininfo::getReqNo, sampleNo)
                        .eq(LabMaininfo::getOrgId, orgId);
                List<LabMaininfo> maininfoList = labMaininfoMapper.selectList(queryWrapper2);
                if (ToolsUtils.isNotEmpty(maininfoList)) {
                    labMaininfo = maininfoList.get(0);
                } else {
                    //标本号查询
                    LambdaQueryWrapper<LabMaininfo> queryWrapper3 = new LambdaQueryWrapper<>();
                    queryWrapper3.eq(LabMaininfo::getDelFlag, 0)
                            .eq(LabMaininfo::getRptGroup, rptGroup)
//                            .ge(LabMaininfo::getSampleda, startTime)
//                            .le(LabMaininfo::getSampleda, endTime)
                            .eq(LabMaininfo::getSampleNo, sampleNo)
                            .eq(LabMaininfo::getOrgId, orgId);
                    List<LabMaininfo> maininfoList1 = labMaininfoMapper.selectList(queryWrapper3);
                    if (ToolsUtils.isNotEmpty(maininfoList1)) {
                        labMaininfo = maininfoList1.get(0);
                    }
                }
                //无工作列表新建工作列表
                if (null == labMaininfo) {
                    labMaininfo = new LabMaininfo();
                    labMaininfo.setRptGroup(rptGroup);
                    labMaininfo.setSampleda(startTime);
                    labMaininfo.setSampleNo(sampleNo);
                    labMaininfo.setTestTime(new Timestamp(System.currentTimeMillis()));
                    labMaininfo.setIsChk(new BigDecimal(0));
                    labMaininfo.setOrgId(orgId);
                    LambdaQueryWrapper<LabMaininfo> lambdaQueryWrappers = new LambdaQueryWrapper<>();
                    lambdaQueryWrappers
                            .eq(LabMaininfo::getSampleNo, sampleNo)
                            .eq(LabMaininfo::getRptGroup, rptGroup)
                            .ge(LabMaininfo::getSampleda, startTime)
                            .le(LabMaininfo::getSampleda, endTime)
                            .eq(LabMaininfo::getOrgId, orgId)
                            .eq(LabMaininfo::getDelFlag, 0);
                    boolean b = labMaininfoService.saveOrUpdate(labMaininfo, lambdaQueryWrappers);
                }
                BigDecimal isChk = labMaininfo.getIsChk();
                if (ToolsUtils.isNotEmpty(isChk) && isChk.intValue() > 0) {
                    delInstrGermResultList.addAll(instrGermResultMap.get(mainInfolist));
                    continue;
                }

                //处理结果列表
                //接口结果列表 //逆序
                List<IntInstrGermResult> intGermResultList = instrGermResultMap.get(mainInfolist)
                        .stream().sorted(Comparator.comparing(IntInstrGermResult::getCreateTime).reversed()).collect(Collectors.toList());
                //根据germNo、isolateNum，germMachineNo antCode去重
                List<IntInstrGermResult> intInstrGermResultList = intGermResultList
                        .stream().collect(Collectors.collectingAndThen(Collectors
                                .toCollection(() -> new TreeSet<>(Comparator.comparing(IntInstrGermResult::getGermNo)
                                        .thenComparing(IntInstrGermResult::getIsolateNum)
                                        .thenComparing(IntInstrGermResult::getGermMachineNo)
                                        .thenComparing(IntInstrGermResult::getAntCode))), ArrayList::new));
                //去重之后需要把去重得数据找出来 放到删除并转移到log表中的集合中
                List<IntInstrGermResult> quchongList = intGermResultList.stream().filter(item -> !intInstrGermResultList.contains(item)).collect(Collectors.toList());
                if (ToolsUtils.isNotEmpty(quchongList)) {
                    delInstrGermResultList.addAll(quchongList);
                }
                //查询微生物结果
                LambdaQueryWrapper<BacTestResult> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(BacTestResult::getDelFlag, 0)
                        .eq(BacTestResult::getRptGroup, rptGroup)
//                        .ge(BacTestResult::getSampleda, startTime)
//                        .le(BacTestResult::getSampleda, endTime)
                        .eq(BacTestResult::getSampleNo, labMaininfo.getSampleNo())
                        .eq(BacTestResult::getOrgId, orgId);
                List<BacTestResult> testResultList = bacTestResultService.list(queryWrapper);

                //查询微生物检验应用流程方案节点
                MPJLambdaWrapper<BacTestWorkFlowNode> queryWorkFlowNodeWrapper = new MPJLambdaWrapper<>();
                String finalRptGroup = rptGroup;
                String finalSampleNo = labMaininfo.getSampleNo();
                LabMaininfo finalLabMaininfo = labMaininfo;
                queryWorkFlowNodeWrapper.selectAll(BacTestWorkFlowNode.class)
                        .innerJoin(BacTestWorkFlow.class, "TF", p -> p.eq(BacTestWorkFlow::getDelFlag, 0)
                                .eq(BacTestWorkFlow::getRptGroup, finalRptGroup)
                                .eq(BacTestWorkFlow::getSampleNo, finalSampleNo)
//                                .ge(BacTestWorkFlow::getSampleda, startTime)
//                                .le(BacTestWorkFlow::getSampleda, endTime)
//                                .eq(BacTestWorkFlow::getReqNo, finalLabMaininfo.getReqNo())
                                .eq(BacTestWorkFlow::getWorkFlowNo, BacTestWorkFlowNode::getTestFlowNo)
                                .eq(BacTestWorkFlow::getOrgId, BacTestWorkFlowNode::getOrgId))
                        .innerJoin(BacWorkFlowNode.class, "FN", p -> p.eq(BacWorkFlowNode::getDelFlag, 0)
                                .eq(BacWorkFlowNode::getFlowNo, BacTestWorkFlowNode::getTestFlowNo)
                                .eq(BacWorkFlowNode::getNodeCode, BacTestWorkFlowNode::getNodeNo)
                                .eq(BacWorkFlowNode::getOrgId, BacTestWorkFlowNode::getOrgId))
                        .innerJoin(BacWorkFlowNodeDict.class, "ND", p -> p.eq(BacWorkFlowNodeDict::getDelFlag, 0)
                                .eq(BacWorkFlowNodeDict::getCode, BacTestWorkFlowNode::getNodeNo)
                                .eq(BacWorkFlowNodeDict::getOrgId, BacTestWorkFlowNode::getOrgId)
                                .eq(BacWorkFlowNodeDict::getPageCode, "RptResultBac"))
                        .eq(BacTestWorkFlowNode::getDelFlag, 0)
                        .eq(BacTestWorkFlowNode::getRptGroup, finalRptGroup)
                        .eq(BacTestWorkFlowNode::getSampleNo, finalSampleNo)
                        .eq(BacTestWorkFlowNode::getOrgId, orgId);
                List<BacTestWorkFlowNode> bacTestWorkFlowNodeList = bacTestWorkFlowNodeMapper.selectList(queryWorkFlowNodeWrapper);
                BacTestWorkFlowNode bacTestWorkFlowNode = null;
                if (ToolsUtils.isNotEmpty(bacTestWorkFlowNodeList)) {
                    bacTestWorkFlowNode = bacTestWorkFlowNodeList.get(0);
                } else {
                    //查找默认方案
                    MPJLambdaWrapper<BacWorkFlowNode> queryFlowNodeWrapper = new MPJLambdaWrapper<>();
                    queryFlowNodeWrapper.selectAll(BacWorkFlowNode.class)
                            .selectAs("bf", BacWorkFlow::getWorkFlowName, BacWorkFlowNode::getFlowNa)
                            .innerJoin(BacWorkFlow.class, "bf", p -> p.eq(BacWorkFlow::getDelFlag, 0)
                                    .eq(BacWorkFlow::getWorkFlowCode, BacWorkFlowNode::getFlowNo).eq(BacWorkFlow::getWorkFlowCode, "mrfa"))
                            .innerJoin(BacWorkFlowNodeDict.class, "nd", p -> p.eq(BacWorkFlowNodeDict::getDelFlag, 0)
                                    .eq(BacWorkFlowNodeDict::getCode, BacWorkFlowNode::getNodeDictNo).eq(BacWorkFlowNodeDict::getPageCode, "RptResultBac"))
                            .eq(BacWorkFlowNode::getDelFlag, 0)
                            .eq(BacWorkFlowNode::getOrgId, orgId);
                    List<BacWorkFlowNode> bacWorkFlowNodeList = bacWorkFlowNodeMapper.selectList(queryFlowNodeWrapper);
                    if (ToolsUtils.isNotEmpty(bacWorkFlowNodeList)) {
                        BacWorkFlowNode bacWorkFlowNode = bacWorkFlowNodeList.get(0);
                        BacTestWorkFlow bacTestWorkFlow = new BacTestWorkFlow();
                        bacTestWorkFlow.setReqNo(labMaininfo.getReqNo());
                        bacTestWorkFlow.setWorkFlowNo(bacWorkFlowNode.getFlowNo());
                        bacTestWorkFlow.setWorkFlowNa(bacWorkFlowNode.getFlowNa());
                        bacTestWorkFlow.setSeq(1);
                        bacTestWorkFlow.setOrgId(labMaininfo.getOrgId());
                        bacTestWorkFlow.setSampleNo(labMaininfo.getSampleNo());
                        bacTestWorkFlow.setSampleda(labMaininfo.getSampleda());
                        bacTestWorkFlow.setRptGroup(rptGroup);
                        bacTestWorkFlowMapper.insert(bacTestWorkFlow);

                        bacTestWorkFlowNode = new BacTestWorkFlowNode();
                        bacTestWorkFlowNode.setOrgId(labMaininfo.getOrgId());
                        bacTestWorkFlowNode.setTestFlowNo(bacWorkFlowNode.getFlowNo());
                        bacTestWorkFlowNode.setNodeNo(bacWorkFlowNode.getNodeCode());
                        bacTestWorkFlowNode.setReqNo(labMaininfo.getReqNo());
                        bacTestWorkFlowNode.setSampleNo(labMaininfo.getSampleNo());
                        bacTestWorkFlowNode.setSampleda(labMaininfo.getSampleda());
                        bacTestWorkFlowNode.setRptGroup(rptGroup);
                        bacTestWorkFlowNodeMapper.insert(bacTestWorkFlowNode);
                    }

                }

                List<BacTestResult> saveOrUpdateResultList = new ArrayList<>();

                //查看上机记录上有没有感染部位信息 如果有 查询感染部位表查出对应的感染部位对象
                BacSiteOfInfectionDict siteOfInfectionDict = null;
                if(ToolsUtils.isNotEmpty(labMaininfo.getInfectSiteNo())){
                    LambdaQueryWrapper<BacSiteOfInfectionDict> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(BacSiteOfInfectionDict::getDelFlag, 0)
                            .eq(BacSiteOfInfectionDict::getCode, labMaininfo.getInfectSiteNo())
                            .eq(BacSiteOfInfectionDict::getOrgId, orgId);
                    List<BacSiteOfInfectionDict> siteOfInfectionDictList = bacSiteOfInfectionDictMapper.selectList(wrapper);
                    if(ToolsUtils.isNotEmpty(siteOfInfectionDictList)){
                        siteOfInfectionDict = siteOfInfectionDictList.get(0);
                    }
                }

                //根据germNo、isolateNum，germMachineNo分组
                //分组后 每一个key 就是一条微生物的数据
                Map<List<Object>, List<IntInstrGermResult>> intGermResultMap
                        = intInstrGermResultList.stream().collect(Collectors.groupingBy(s -> Arrays.asList(s.getGermNo(), s.getIsolateNum(), s.getGermMachineNo())));

                for (List<Object> germInfolist : intGermResultMap.keySet()) {
                    String germNo = "";
                    String isolateNum = "";
                    String germMachineNo = "";
                    if (ToolsUtils.isNotEmpty(germInfolist.get(0))) {
                        germNo = String.valueOf(germInfolist.get(0));
                    }
                    if (ToolsUtils.isNotEmpty(germInfolist.get(1))) {
                        isolateNum = String.valueOf(germInfolist.get(1));
                    }
                    if (ToolsUtils.isNotEmpty(germInfolist.get(2))) {
                        germMachineNo = String.valueOf(germInfolist.get(2));
                    }
                    if (ToolsUtils.isNotEmpty(germNo) && ToolsUtils.isNotEmpty(isolateNum) && ToolsUtils.isNotEmpty(germMachineNo)) {

                        List<IntInstrGermResult> intInstrGermResults = intGermResultMap.get(germInfolist);

                        //根据 germMachineNo与germNo查找对照表
                        MPJLambdaWrapper<BacGermDict> queryGermDictWrapper = new MPJLambdaWrapper<>();
                        String finalGermNo = germNo;
                        String finalGermMachineNo = germMachineNo;
                        String finalOrgId = orgId;
                        queryGermDictWrapper.selectAll(BacGermDict.class)
                                .innerJoin(BacInstrGermDict.class, p -> p.eq(BacInstrGermDict::getInstrCode, finalGermMachineNo)
                                        .eq(BacInstrGermDict::getInputGermNo, finalGermNo)
                                        .eq(BacInstrGermDict::getOrgId, finalOrgId)
                                        .eq(BacInstrGermDict::getDelFlag, 0)
                                        .eq(BacInstrGermDict::getGermNo, BacGermDict::getGermNo))
                                .eq(BacGermDict::getDelFlag, 0);
                        List<BacGermDict> germDictList = bacGermDictMapper.selectJoinList(BacGermDict.class, queryGermDictWrapper);

                        if (ToolsUtils.isNotEmpty(germDictList)) {
                            BacTestResult bacTestResult;
                            BacGermDict bacGermDict = germDictList.get(0);
                            String finalIsolateNum = isolateNum;
                            Optional<BacTestResult> testResultOptional = testResultList.stream().filter(item -> ToolsUtils.isNotEmpty(item.getIsolateNum()) && item.getIsolateNum().equals(finalIsolateNum) && item.getGermNo().equals(bacGermDict.getGermNo())).findFirst();
                            if (testResultOptional.isPresent()) {
                                bacTestResult = testResultOptional.get();
                            } else {
                                bacTestResult = new BacTestResult();
                                bacTestResult.setSampleda(labMaininfo.getSampleda());
                                bacTestResult.setSampleNo(labMaininfo.getSampleNo());
                                bacTestResult.setRptGroup(rptGroup);
                                bacTestResult.setOrgId(finalOrgId);
                                bacTestResult.setIsolateNum(isolateNum);
                                bacTestResult.setGermNo(bacGermDict.getGermNo());
                                bacTestResult.setGermNa(bacGermDict.getGermNa());
                                if (ToolsUtils.isNotEmpty(bacTestWorkFlowNode)) {
                                    bacTestResult.setTestFlowNo(bacTestWorkFlowNode.getTestFlowNo());
                                    bacTestResult.setTestNodeNo(bacTestWorkFlowNode.getNodeNo());
                                }
                                bacTestResult.setOperateDate(new Timestamp(new Date().getTime()));//
                                bacTestResult.setInfeSiteNo(labMaininfo.getInfectSiteNo());
                                if(ToolsUtils.isNotEmpty(siteOfInfectionDict)){
                                    bacTestResult.setInfeSiteNa(siteOfInfectionDict.getName());
                                }
                                if(ToolsUtils.isNotEmpty(intInstrGermResults)){
                                    bacTestResult.setInstrCode(intInstrGermResults.get(0).getInstrCode());
                                }
                                bacTestResult.setGermMachineNo(germMachineNo);
                            }

                            saveOrUpdateResultList.add(bacTestResult);
                            //保存完微生物结果后 再取出抗生素数据

                            //根据上机记录以及微生物数据查出抗生素数据
                            LambdaQueryWrapper<BacDrugTestResult> queryDrugTestResultWrapper = new LambdaQueryWrapper<>();
                            queryDrugTestResultWrapper.eq(BacDrugTestResult::getDelFlag, 0)
                                    .eq(BacDrugTestResult::getRptGroup, rptGroup)
//                                    .ge(BacDrugTestResult::getSampleda, startTime)
//                                    .le(BacDrugTestResult::getSampleda, endTime)
                                    .eq(BacDrugTestResult::getSampleNo, labMaininfo.getSampleNo())
                                    .eq(BacDrugTestResult::getOrgId, orgId)
                                    .eq(BacDrugTestResult::getIsolateNum, isolateNum)
                                    .eq(BacDrugTestResult::getGermNo, bacGermDict.getGermNo());
                            List<BacDrugTestResult> bacDrugTestResultList = bacDrugTestResultService.list(queryDrugTestResultWrapper);

                            List<BacDrugTestResult> saveOrUpdateDrugResultList = new ArrayList<>();
                            for (IntInstrGermResult intInstrGermResult : intInstrGermResults) {
                                //根据 germMachineNo与antCode查找对照表
                                String antCode = intInstrGermResult.getAntCode();
                                String resultOrgId = intInstrGermResult.getOrgId();

                                MPJLambdaWrapper<BacAntibioticsDict> queryAntibDictWrapper = new MPJLambdaWrapper<>();
                                queryAntibDictWrapper.selectAll(BacAntibioticsDict.class)
                                        .innerJoin(BacInstrAntibDict.class, p -> p.eq(BacInstrAntibDict::getInputAntCode, antCode)
                                                .eq(BacInstrAntibDict::getInstrCode, finalGermMachineNo)
                                                .eq(BacInstrAntibDict::getOrgId, resultOrgId)
                                                .eq(BacInstrAntibDict::getDelFlag, 0)
                                                .eq(BacInstrAntibDict::getAntCode, BacAntibioticsDict::getAntCode))
                                        .eq(BacAntibioticsDict::getDelFlag, 0);
                                List<BacAntibioticsDict> antibDictList = bacAntibioticsDictMapper.selectJoinList(BacAntibioticsDict.class, queryAntibDictWrapper);
                                if (ToolsUtils.isNotEmpty(antibDictList)) {
                                    BacDrugTestResult bacDrugTestResult;
                                    //查看结果表中是否有结果
                                    BacAntibioticsDict bacAntibioticsDict = antibDictList.get(0);
                                    Optional<BacDrugTestResult> firstDrugTestResult = bacDrugTestResultList.stream().filter(item -> item.getAntNo().equals(bacAntibioticsDict.getAntCode())).findFirst();
                                    if (firstDrugTestResult.isPresent()) {
                                        bacDrugTestResult = firstDrugTestResult.get();
                                    } else {
                                        bacDrugTestResult = new BacDrugTestResult();
                                        bacDrugTestResult.setSampleda(labMaininfo.getSampleda());
                                        bacDrugTestResult.setSampleNo(labMaininfo.getSampleNo());
                                        bacDrugTestResult.setRptGroup(rptGroup);
                                        bacDrugTestResult.setOrgId(finalOrgId);
                                        bacDrugTestResult.setIsolateNum(isolateNum);
                                        bacDrugTestResult.setDataFrom("1");
                                        bacDrugTestResult.setSeq(intInstrGermResult.getDisplayOrder());
                                        if (ToolsUtils.isNotEmpty(intInstrGermResult.getBreakPoint())) {
                                            bacDrugTestResult.setIsBpFromInstr(1);
                                            bacDrugTestResult.setBreakPoint(intInstrGermResult.getBreakPoint());
                                        }
                                        bacDrugTestResult.setGermNo(bacGermDict.getGermNo());
                                        bacDrugTestResult.setAntNo(bacAntibioticsDict.getAntCode());
                                        bacDrugTestResult.setAntNa(bacAntibioticsDict.getAntName());
                                        bacDrugTestResult.setPotency(bacAntibioticsDict.getVerificationPrice());
                                        if (ToolsUtils.isNotEmpty(bacTestWorkFlowNode)) {
                                            bacDrugTestResult.setTestFlowNo(bacTestWorkFlowNode.getTestFlowNo());
                                            bacDrugTestResult.setTestNodeNo(bacTestWorkFlowNode.getNodeNo());
                                        }
                                    }
                                    bacDrugTestResult.setTestResult(intInstrGermResult.getResult());
                                    bacDrugTestResult.setDrugMthNo(intInstrGermResult.getAstTestMethod());
                                    bacDrugTestResult.setSensitiveNo(intInstrGermResult.getInterpretaionNo());
                                    bacDrugTestResult.setSensitiveFrom("仪器");
                                    bacDrugTestResult.setAntRecomGroupId(intInstrGermResult.getDrugProposalGroup());
                                    bacDrugTestResult.setIntResultId(intInstrGermResult.getId());
                                    bacDrugTestResult.setInterpretaionNo(intInstrGermResult.getInterpretaionNo());
                                    bacDrugTestResult.setInstrCode(intInstrGermResult.getInstrCode());
                                    bacDrugTestResult.setGermMachineNo(intInstrGermResult.getGermMachineNo());
                                    saveOrUpdateDrugResultList.add(bacDrugTestResult);

                                    //将成功插入结果表中得数据转移到log表中
                                    delInstrGermResultList.add(intInstrGermResult);


                                } else {
                                    //无通道号
                                    intInstrGermResult.setIsNoChannel("A");
                                    noChannelResultList.add(intInstrGermResult);
                                }

                            }//抗生素循环结束
                            if (ToolsUtils.isNotEmpty(saveOrUpdateDrugResultList)) {
                                boolean isCalcBP = false;
                                boolean isCalcIC = false;
                                try {

                                    //仪器数据是否重新计算折点
                                    SysParamParam sysp2 = new SysParamParam();
                                    sysp2.setParamCode("bgdyxtcs");
                                    sysp2.setField("instrDataIsCalcBP");
                                    sysp2.setClassifyCode(rptGroup);
                                    sysp2.setOrgId(orgId);
                                    List<SysParamFieldValueDto> instrDataIsCalcBPLst = sysParamValueService.findSysParamFieldAndValueListByCode(sysp2);
                                    if (!instrDataIsCalcBPLst.isEmpty()) {
                                        if (instrDataIsCalcBPLst.get(0).getValue().equals("1")) {
                                            isCalcBP = true;
                                        }
                                    }

                                    //仪器数据是否重新计算敏感性
                                    SysParamParam sysp1 = new SysParamParam();
                                    sysp1.setParamCode("bgdyxtcs");
                                    sysp1.setField("instrDataIsCalcIC");
                                    sysp1.setClassifyCode(rptGroup);
                                    sysp1.setOrgId(orgId);

                                    List<SysParamFieldValueDto> instrDataIsCalcICLst = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1);
                                    if (!instrDataIsCalcICLst.isEmpty()) {
                                        if (instrDataIsCalcICLst.get(0).getValue().equals("1")) {
                                            isCalcIC = true;
                                        }
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                /*计算折点*/
                                for (BacDrugTestResult m : saveOrUpdateDrugResultList) {
                                    String notReportSensitiveNo = null;
                                    //判断是否是不出报告的药敏
                                    if(ToolsUtils.isNotEmpty(labMaininfo)){
                                        notReportSensitiveNo = bacDrugTestResultService.judgeDrugNotReport(m,labMaininfo);
                                    }
                                    //判断是否符合天然耐药规则
                                    bacDrugTestResultService.judgeNaturalMdrRule(m);
                                    Integer isNaturlResis = m.getIsNaturlResis();
                                    //1是天然耐药
                                    if(!(ToolsUtils.isNotEmpty(isNaturlResis)&&isNaturlResis==1)&&ToolsUtils.isEmpty(notReportSensitiveNo)){
                                        //查看此结果是否符合药敏结果敏感性规则
                                        String sensitiveNo = bacDrugTestResultService.judgeSensitiveResultRule(m,isCalcIC);
                                        if(ToolsUtils.isEmpty(sensitiveNo)){
                                            List<BacTestResult> geermObjs = saveOrUpdateResultList.stream().filter(p ->
                                                            p.getSampleda().equals(m.getSampleda())
                                                                    && p.getSampleNo().equals(m.getSampleNo())
                                                                    && p.getRptGroup().equals(m.getRptGroup())
                                                                    && p.getTestFlowNo().equals(m.getTestFlowNo())
                                                                    && p.getTestNodeNo().equals(m.getTestNodeNo())
                                                                    && p.getGermNo().equals(m.getGermNo()))
                                                    .collect(Collectors.toList());
                                            if (ToolsUtils.isNotEmpty(geermObjs)) {
                                                bacBreakPointCalcService.setApplicableBreakpoint(geermObjs.get(0), Arrays.asList(m), isCalcBP, isCalcIC);
                                            }

                                            //计算完折点后需要根据药敏结果敏感性规则判断该药敏是否符合敏感性规则，如果符合则只修改药敏的敏感性
                                            //dataFrom为1（仪器数据）并且isCalcIC(是否从新计算敏感性)为true 则需要重新按照规则计算敏感性
                                            if(isCalcIC){
                                                judgeResultSenroleRuleByIntInstr(m,saveOrUpdateDrugResultList);
                                            }
                                        }
                                    }
                                }

                                boolean isSaveOrupdate = bacDrugTestResultService.saveOrUpdateBatch(saveOrUpdateDrugResultList);
                            }

                        } else {
                            //无通道号
                            //List<IntInstrGermResult> intInstrGermResults = intGermResultMap.get(germInfolist);
                            for (IntInstrGermResult intInstrGermResult : intInstrGermResults) {
                                intInstrGermResult.setIsNoChannel("G");
                                noChannelResultList.add(intInstrGermResult);
                            }

                        }
                    }
                }//分组后循环结束

                if (ToolsUtils.isNotEmpty(saveOrUpdateResultList)) {
                    boolean isSaveOrupdate = bacTestResultService.saveOrUpdateBatch(saveOrUpdateResultList);
                }
            }//sampleDa,prtGroup,sampleNo都不为空

        }//循环结束

        if (ToolsUtils.isNotEmpty(delInstrGermResultList)) {
            //删除
            List<String> ids = delInstrGermResultList.stream().map(IntInstrGermResult::getId).collect(Collectors.toList());
            this.removeByIds(ids);
            //插入log
            List<IntInstrGermResultLog> addLogList = new ArrayList<>();
            for (IntInstrGermResult iResult : delInstrGermResultList) {
                IntInstrGermResultLog resultLog = new IntInstrGermResultLog();
                BeanUtil.copyProperties(iResult, resultLog, "id");
                resultLog.setInstrGermResultId(iResult.getId());
                addLogList.add(resultLog);
            }
            intInstrGermResultLogService.saveBatch(addLogList);
        }
        if (ToolsUtils.isNotEmpty(noChannelResultList)) {
            this.updateBatchById(noChannelResultList);
        }

    }
    @Autowired
    BacDrugResultSenroleMapper bacDrugResultSenroleMapper;
    @Autowired
    BacDrugResultSenroleDetailsMapper bacDrugResultSenroleDetailsMapper;
    private void judgeResultSenroleRuleByIntInstr(BacDrugTestResult bacDrugTestResult, List<BacDrugTestResult> bacDrugResultList) {
        String antNo = bacDrugTestResult.getAntNo();
        if(ToolsUtils.isNotEmpty(antNo)){
            //查出药敏结果敏感性规则
            MPJLambdaWrapper<BacDrugResultSenrole> queryResultSenroleWrapper = new MPJLambdaWrapper<>();
            queryResultSenroleWrapper.selectAll(BacDrugResultSenrole.class)
                    .selectAs(BacInterpretationCodeDict::getName, BacDrugResultSenrole::getSensitiveNa)
                    .selectAs(BacInterpretationCodeDict::getDisplayColor, BacDrugResultSenrole::getDisplayColor)
                    .leftJoin(BacInterpretationCodeDict.class, "sa",
                            p -> p.eq(BacInterpretationCodeDict::getCode, BacDrugResultSenrole::getSensitiveNo).eq(BacInterpretationCodeDict::getDelFlag, 0));
            queryResultSenroleWrapper.eq(BacDrugResultSenrole::getDelFlag, 0)
                    .eq(BacDrugResultSenrole::getAntNo, antNo);
            List<BacDrugResultSenrole> ruleList = bacDrugResultSenroleMapper.selectList(queryResultSenroleWrapper);
            if(ToolsUtils.isNotEmpty(ruleList)){
                //取出rulelist中的所有rolecode集合
                List<String> roleCodeList = ruleList.stream().map(BacDrugResultSenrole::getRoleCode).collect(Collectors.toList());
                //根据rolecode集合查出所有规则明细
                MPJLambdaWrapper<BacDrugResultSenroleDetails> querySenroleDetailWrapper = new MPJLambdaWrapper<>();
                querySenroleDetailWrapper.selectAll(BacDrugResultSenroleDetails.class)
                        .eq(BacDrugResultSenroleDetails::getDelFlag, 0)
                        .in(BacDrugResultSenroleDetails::getRoleCode, roleCodeList);
                List<BacDrugResultSenroleDetails> senroleDetailList = bacDrugResultSenroleDetailsMapper.selectList(querySenroleDetailWrapper);
                if(ToolsUtils.isNotEmpty(senroleDetailList)){
                    //获取senroleDetailsList中所有的antno
                    List<String> antNoList = senroleDetailList.stream().map(BacDrugResultSenroleDetails::getAntNo).collect(Collectors.toList());
                    //从bacDrugResultList查出所有的antno对应的结果
                    List<BacDrugTestResult> bacDrugTestResultList = bacDrugResultList.stream().filter(m -> antNoList.contains(m.getAntNo())).collect(Collectors.toList());
                    if(ToolsUtils.isNotEmpty(bacDrugTestResultList)){
                        //根据rolecode分组
                        Map<String, List<BacDrugResultSenroleDetails>> roleCodeMap = senroleDetailList.stream().collect(Collectors.groupingBy(BacDrugResultSenroleDetails::getRoleCode));
                        for (String entry : roleCodeMap.keySet()) {
                            List<BacDrugResultSenroleDetails> detailsList = roleCodeMap.get(entry);
                            Boolean isCalcFlag = true;
                            //循环每组的规则明细
                            for (BacDrugResultSenroleDetails roleDetail : detailsList) {
                                //获取规则的敏感性
                                String roleSensitiveNo = roleDetail.getSensitiveNo();
                                if(ToolsUtils.isNotEmpty(roleSensitiveNo)){
                                    //从药敏结果中查出此药敏的结果
                                    List<BacDrugTestResult> testResultList = bacDrugTestResultList.stream().filter(m -> m.getAntNo().equals(roleDetail.getAntNo())).collect(Collectors.toList());
                                    if(ToolsUtils.isNotEmpty(testResultList)){
                                        BacDrugTestResult testResult = testResultList.get(0);
                                        String testSensitiveNo = testResult.getSensitiveNo();
                                        if(ToolsUtils.isNotEmpty(testSensitiveNo)){
                                            if(!roleSensitiveNo.equals(testSensitiveNo)){
                                                isCalcFlag=false;
                                            }
                                        }else {
                                            isCalcFlag=false;
                                        }
                                    }else {
                                        isCalcFlag=false;
                                    }
                                }else {
                                    isCalcFlag=false;
                                }
                            }
                            if(isCalcFlag){
                                //根据entry 获取规则
                                BacDrugResultSenrole role = ruleList.stream().filter(m -> m.getRoleCode().equals(entry)).collect(Collectors.toList()).get(0);
                                String roleSensitiveNo = role.getSensitiveNo();
                                if(ToolsUtils.isNotEmpty(roleSensitiveNo)){
                                    bacDrugTestResult.setSensitiveNo(roleSensitiveNo);
                                    bacDrugTestResult.setInterpNa(role.getSensitiveNa());
                                    bacDrugTestResult.setInterpDisplayColor(role.getDisplayColor());
                                    bacDrugTestResult.setSensitiveFrom(role.getRoleName());
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    @Autowired
    SysParamValueService sysParamValueService;
    @Override
    public Result findInstrGermResultNoChannelList(IntInstrResultParam param) {
        MPJLambdaWrapper<IntInstrGermResult> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(IntInstrGermResult.class)
                .ne(IntInstrGermResult::getIsNoChannel, "N")
                .eq(IntInstrGermResult::getSampleNo, param.getSampleNo())
                .eq(IntInstrGermResult::getRptGroup, param.getRptGroup());
//        if (ToolsUtils.isNotEmpty(param.getSampleDaStr())) {
//            Timestamp startTime = Timestamp.valueOf(param.getSampleDaStr() + " 00:00:00");
//            Timestamp endTime = Timestamp.valueOf(param.getSampleDaStr() + " 23:59:59");
//            queryWrapper.ge(IntInstrGermResult::getSampleda, startTime);
//            queryWrapper.le(IntInstrGermResult::getSampleda, endTime);
//        }
        List<IntInstrGermResult> noChannelList = intInstrGermResultMapper.selectList(queryWrapper);
        Map<String, Object> returnMap = new HashMap<>();

        if (ToolsUtils.isNotEmpty(noChannelList)) {
            //G 细菌没有对照
            List<IntInstrGermResult> GList = noChannelList.stream().filter(s -> "G".equals(s.getIsNoChannel())).collect(Collectors.toList());
            if (ToolsUtils.isNotEmpty(GList)) {
                //根据germMachineNo，rptGroup，germNa 去重 获取新的list
                List<IntInstrGermResult> newGList = GList.stream().collect(Collectors.groupingBy(s -> Arrays.asList(s.getGermMachineNo(), s.getRptGroup(), s.getGermNo()))).entrySet().stream().map(s -> s.getValue().get(0)).collect(Collectors.toList());
                returnMap.put("noChanneGermList", newGList);
            }

            //A 抗生素没有对照
            List<IntInstrGermResult> AList = noChannelList.stream().filter(s -> "A".equals(s.getIsNoChannel())).collect(Collectors.toList());
            if (ToolsUtils.isNotEmpty(AList)) {
                List<IntInstrGermResult> newAList = AList.stream().collect(Collectors.groupingBy(s -> Arrays.asList(s.getGermMachineNo(), s.getRptGroup(), s.getGermNo(), s.getAntCode()))).entrySet().stream().map(s -> s.getValue().get(0)).collect(Collectors.toList());

                returnMap.put("noChanneAntList", newAList);

            }

        }
        return Result.succ(1, "查询成功", returnMap);
    }

    @Override
    public Result findGermAndAntDictlList(IntInstrResultParam param) {

        Map<String, Object> returnMap = new HashMap<>();
        //查出所有细菌
        MPJLambdaWrapper<BacGermDict> queryBacGermWrapper = new MPJLambdaWrapper<>();
        queryBacGermWrapper.selectAll(BacGermDict.class)
                .eq(BacGermDict::getDelFlag, 0);
        List<BacGermDict> germDictList = bacGermDictMapper.selectList(queryBacGermWrapper);
        if (ToolsUtils.isNotEmpty(germDictList)) {
            returnMap.put("germDictList", germDictList);
        }

        //查出所有抗生素
        MPJLambdaWrapper<BacAntibioticsDict> queryBacAntibioticsWrapper = new MPJLambdaWrapper<>();
        queryBacAntibioticsWrapper.selectAll(BacAntibioticsDict.class)
                .eq(BacAntibioticsDict::getDelFlag, 0);
        List<BacAntibioticsDict> antibioticsDictList = bacAntibioticsDictMapper.selectList(queryBacAntibioticsWrapper);
        if (ToolsUtils.isNotEmpty(antibioticsDictList)) {
            returnMap.put("antDictList", antibioticsDictList);
        }


        return Result.succ(1, "查询成功", returnMap);
    }

    @Override
    public Result saveBacthGermNoChannelResult(IntinstrGermReusltDto dto) {
        List<IntInstrGermResult> noChanneGermResultlList = dto.getNoChanneGermResultlList();
        for (IntInstrGermResult noChannelGermResult : noChanneGermResultlList) {
            BacInstrGermDict germDict = new BacInstrGermDict();
            germDict.setSeq(new BigDecimal(1));
            germDict.setInstrCode(noChannelGermResult.getGermMachineNo());
            germDict.setGermNo(noChannelGermResult.getGermDictNo());
            germDict.setInputGermNo(noChannelGermResult.getGermNo());
            germDict.setInputGermNa(noChannelGermResult.getGermNa());

            LambdaQueryWrapper<BacInstrGermDict> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(BacInstrGermDict::getInstrCode, noChannelGermResult.getGermMachineNo())
                    .eq(BacInstrGermDict::getInputGermNo, noChannelGermResult.getGermNo())
                    .eq(BacInstrGermDict::getDelFlag, 0);
            boolean b = bacInstrGermDictService.saveOrUpdate(germDict, queryWrapper);
            if (b) {
                //更新数据
                LambdaUpdateWrapper<IntInstrGermResult> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                lambdaUpdateWrapper.set(IntInstrGermResult::getIsNoChannel, "N")
                        .eq(IntInstrGermResult::getRptGroup, noChannelGermResult.getRptGroup())
                        .eq(IntInstrGermResult::getGermMachineNo, noChannelGermResult.getGermMachineNo())
                        .eq(IntInstrGermResult::getGermNo, noChannelGermResult.getGermNo())
                        .eq(IntInstrGermResult::getIsNoChannel, "G");

                int update = intInstrGermResultMapper.update(null, lambdaUpdateWrapper);
            }
        }
        List<IntInstrGermResult> noChanneAntResultlList = dto.getNoChanneAntResultlList();

        for (IntInstrGermResult noChannelAntResult : noChanneAntResultlList) {
            BacInstrAntibDict antibDict = new BacInstrAntibDict();
            antibDict.setSeq(new BigDecimal(1));
            antibDict.setInstrCode(noChannelAntResult.getGermMachineNo());
            antibDict.setAntCode(noChannelAntResult.getAntDictNo());
            antibDict.setInputAntCode(noChannelAntResult.getAntCode());
            antibDict.setInputAntNa(noChannelAntResult.getAntName());

            LambdaQueryWrapper<BacInstrAntibDict> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(BacInstrAntibDict::getInstrCode, noChannelAntResult.getGermMachineNo())
                    .eq(BacInstrAntibDict::getInputAntCode, noChannelAntResult.getAntCode())
                    .eq(BacInstrAntibDict::getDelFlag, 0);
            boolean b = bacInstrAntibDictService.saveOrUpdate(antibDict, queryWrapper);
            if (b) {
                //更新数据
                LambdaUpdateWrapper<IntInstrGermResult> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                lambdaUpdateWrapper.set(IntInstrGermResult::getIsNoChannel, "N")
                        .eq(IntInstrGermResult::getRptGroup, noChannelAntResult.getRptGroup())
                        .eq(IntInstrGermResult::getGermMachineNo, noChannelAntResult.getGermMachineNo())
                        .eq(IntInstrGermResult::getAntCode, noChannelAntResult.getAntCode())
                        .eq(IntInstrGermResult::getIsNoChannel, "A");

                int update = intInstrGermResultMapper.update(null, lambdaUpdateWrapper);
            }
        }

        return Result.succ(1, "处理成功", null);

    }

    @Autowired
    BacInstrGermDictService bacInstrGermDictService;
    @Autowired
    BacInstrAntibDictService bacInstrAntibDictService;
}
